<template>
  <a-modal
    class="add-modal"
    :visible="addVisible"
    :maskClosable="false"
    :destroyOnClose="true"
    :keyboard="false"
    title="新增海报主图"
    @cancel="closeModal(false)"
    @ok="handSubmit"
    :confirmLoading="confirmLoading || tableLoading"
    width="600px"
  >
    <a-spin tip="Loading..." :spinning="tableLoading">
      <a-form-model
        ref="pictureForm"
        :model="pictureForm"
        :rules="rules"
        v-bind="layout"
      >
        <a-form-model-item has-feedback label="主图名称" prop="pictureName">
          <a-input
            v-model="pictureForm.pictureName"
            autocomplete="off"
            placeholder="请输入主图名称"
            style="width: 200px"
          />
        </a-form-model-item>
        <div style="display: flex; justify-content: left; margin-left: 60px">
          <a-form-model-item has-feedback label="选择分类" prop="firstId">
            <a-select
              style="width: 200px; transform: translateX(6px)"
              :options="firstOptions"
              v-model="pictureForm.firstId"
              @change="firstOptionsChange"
              placeholder="请选择一级分类"
            />
          </a-form-model-item>
          <a-form-model-item
            has-feedback
            label=""
            prop="secondId"
            v-if="secondOptions && secondOptions.length > 0"
          >
            <a-select
              style="width: 200px; margin-left: 6px"
              :options="secondOptions"
              v-model="pictureForm.secondId"
              placeholder="请选择二级分类"
            />
          </a-form-model-item>
        </div>
        <a-form-model-item label="选择关联产品" prop="product">
          <div
            v-if="pictureForm.product && pictureForm.product.length == 0"
            class="product"
            @click="addProduct"
          >
            选择产品
          </div>
          <div v-else>
            <div class="product" @click="addProduct">增加产品</div>
            <a-table
              :columns="columns"
              :data-source="pictureForm.product"
              bordered
              :pagination="false"
              rowKey="id"
            >
              <template slot="tableOperation" slot-scope="text, record">
                <a-space>
                  <a
                    href="javascript:;"
                    class="text-danger"
                    @click="deleteProduct(record.id)"
                    >删除</a
                  >
                </a-space>
              </template>
            </a-table>
          </div>
        </a-form-model-item>

        <a-form-model-item label="主图" prop="mainPicture">
          <div style="position: relative">
            <div
              v-if="pictureForm.mainPicture"
              @click="openUpload('image', pictureForm)"
              class="upload_wrap"
              :style="{
                background: `url(${pictureForm.mainPicture}) no-repeat 50% 50%/cover`,
              }"
            >
              <p class="updateImg">更换图片</p>
            </div>
            <div
              v-else
              class="upload_wrap uploadBox"
              @click="openUpload('image', pictureForm)"
            >
              <a-icon type="plus" />
              <p>上传图片</p>
            </div>
            <div class="patation">tips：建议尺寸750px*562px（比例4:3）</div>
          </div>
        </a-form-model-item>

        <a-form-model-item has-feedback label="排序" prop="sort">
          <a-input-number
            :precision="0"
            v-model="pictureForm.sort"
            placeholder="填写整数"
            style="width: 200px"
          />
        </a-form-model-item>
      </a-form-model>
    </a-spin>

    <video-modal
      :visible="visibleModal"
      @cancel="closeInfoModal"
      :ContentType="ContentType"
      :fileSize="fileSize"
      @upload="upload"
      :videoData="videoData"
    ></video-modal>
    <addProduct
      :productVisible="productVisible"
      @cancel="closeProductModal"
      @comfirm="comfirmProduct"
      :chooseIdList="[...pictureForm.product]"
    ></addProduct>
  </a-modal>
</template>
<script>
import videoModal from "@/components/antBase/videoModal";
import addProduct from "./addProduct.vue";
export default {
  name: "AddPosterPictureModal",
  components: {
    videoModal,
    addProduct,
  },
  props: {
    addVisible: {
      // 是否显示弹窗
      type: Boolean,
      default: false,
    },
    // 编辑数据id
    editRowId: {
      type: [String, Number],
      default: "",
    },
    // 一级分类名称
    firstName: {
      type: [String],
      default: "",
    },
  },
  computed: {
    proType() {
      return (type) => {
        switch (+type) {
          case 1:
            return "图库";
          case 2:
            return "案例";
          case 3:
            return "视频";
        }
      };
    },
  },
  watch: {
    addVisible(y) {
      if (y) {
        if (this.editRowId) {
          this.selDate();
        }
      } else {
        this.pictureForm = {
          pictureName: "",
          product: [],
          mainPicture: "",
          sort: "",
          firstId: undefined,
          secondId: undefined,
        };
        this.secondOptions = [];
        this.confirmLoading = false;
      }
    },
  },
  data() {
    return {
      columns: [
        {
          title: "名称",
          dataIndex: "name",
          key: "name",
          align: "center",
        },
        {
          title: "类型",
          dataIndex: "type",
          key: "type",
          align: "center",
          customRender: (text, row) => {
            return this.proType(text);
          },
        },
        {
          title: "操作",
          dataIndex: "operation",
          align: "center",
          scopedSlots: { customRender: "tableOperation" },
        },
      ],
      layout: {
        labelCol: { span: 6 },
        wrapperCol: { span: 18 },
      },
      pictureForm: {
        pictureName: "",
        product: [],
        mainPicture: "",
        sort: "",
        firstId: undefined,
        secondId: undefined,
      },
      rules: {
        pictureName: [
          {
            required: true,
            message: "主图名称不能为空",
            trigger: "change",
          },
          {
            min: 2,
            max: 16,
            message: "主图名称为2-16位",
            trigger: "change",
          },
        ],
        firstId: [
          {
            required: true,
            message: "请选择一级分类",
            trigger: "change",
          },
        ],
        secondId: [
          {
            required: true,
            message: "请选择二级分类",
            trigger: "change",
          },
        ],
        product: [
          {
            type: "array",
            required: true,
            message: "请选择关联产品",
            trigger: "change",
          },
        ],
        mainPicture: [
          {
            required: true,
            message: "请上传主图",
            trigger: "change",
          },
        ],
        sort: [
          {
            required: true,
            message: "请填写排序",
            trigger: "change",
          },
        ],
      },
      visibleModal: false,
      ContentType: "image",
      fileSize: 1,
      videoData: {},
      productVisible: false,
      firstOptions: [],
      secondOptions: [],
      secondCategoryInfo: {},
      confirmLoading: false,
      firstList: [],
      tableLoading: false,
    };
  },
  mounted() {
    this.getPosterCategoryList();
  },
  methods: {
    // 一级分类改变
    firstOptionsChange(value) {
      this.pictureForm.secondId = undefined;
      if (
        !this.secondCategoryInfo[value] ||
        this.secondCategoryInfo[value]?.length == 0
      ) {
        // 没有二级分类 把二级分类下拉选项数组置空
        this.secondOptions = [];
        return;
      }
      this.secondOptions = this.secondCategoryInfo[value]?.map((item) => {
        // 获取当前选择一级分类下二级分类
        return {
          label: item.name,
          value: item.id,
        };
      });
    },
    // 查询分类数据
    async getPosterCategoryList() {
      const res = await this.$get(
        "goldenhome/gh/poster_admin/poster/category/list",
        {
          source: 2,
        }
      );
      if (res && res.returnCode == 1000) {
        this.firstList = res?.dataInfo || [];
        this.firstOptions = res.dataInfo.map((item) => {
          return {
            label: item.name,
            value: item.id,
          };
        });
        res.dataInfo.forEach((item) => {
          this.secondCategoryInfo[item.id] = item.children;
        });
      }
    },
    // 查询数据
    async selDate() {
      this.tableLoading = true;
      const res = await this.$get("goldenhome/gh/poster_admin/poster/id", {
        id: this.editRowId,
      });
      const dataInfo = res.dataInfo;
      this.pictureForm.firstId = this.firstOptions.find((item) => {
        return item.label == this.firstName;
      })?.value;
      this.secondOptions = (
        this.secondCategoryInfo[this.pictureForm.firstId] || []
      ).map((item) => {
        // 获取当前选择一级分类下二级分类
        return {
          label: item.name,
          value: item.id,
        };
      });
      this.pictureForm.secondId =
        (this.secondCategoryInfo[this.pictureForm.firstId] &&
          dataInfo?.posterCategoryId) ||
        undefined;
      if (res.returnCode == 1000) {
        this.pictureForm = {
          ...this.pictureForm,
          id: dataInfo.id,
          pictureName: dataInfo.name,
          product: (dataInfo?.products || [])?.map((item) => {
            return {
              name: item.productName,
              id: item.productId,
              type: item.productType,
            };
          }),
          mainPicture: dataInfo.imgsUrl,
          sort: dataInfo.sort,
        };
        this.tableLoading = false;
      }
    },
    // 新增数据(新增和更新)
    async disposeData() {
      this.confirmLoading = true;
      let param = {
        id: this.pictureForm.id,
        posterCategoryId: this.pictureForm.secondId || this.pictureForm.firstId,
        name: this.pictureForm.pictureName,
        products: this.pictureForm?.product.map((item) => {
          return {
            productName: item.name,
            productId: item.id,
            productType: item.type,
          };
        }),
        sort: this.pictureForm.sort,
        imgsUrl: this.pictureForm.mainPicture,
      };
      try {
        if (this.pictureForm.id) {
          await this.$post("goldenhome/gh/poster_admin/poster/update", {
            ...param,
          });
        } else {
          await this.$post("goldenhome/gh/poster_admin/poster/add", {
            ...param,
          });
        }

        this.$emit("confirm");
        this.closeModal();
      } catch (e) {
        this.confirmLoading = false;
      }
    },
    // 打开上传组件
    openUpload(a, b) {
      if (a == "image") {
        this.checkValue = { imgUrl: this.pictureForm.mainPicture };
      }
      this.ContentType = a;
      this.visibleModal = true;
    },
    upload(val) {
      this.visibleModal = false;
      this.videoData = val;
      this.$set(this.pictureForm, "mainPicture", val.fileUrl);
    },
    closeModal(bool) {
      this.$emit("cancel", bool);
    },
    handSubmit() {
      this.$refs.pictureForm.validate((valid) => {
        if (valid) {
          this.disposeData();
        } else {
          console.log("error submit!!");
          return false;
        }
      });
    },
    // 关闭上传图片弹窗
    closeInfoModal(type) {
      this.visibleModal = false;
    },
    // 打开选择关联产品弹窗
    addProduct() {
      this.productVisible = true;
    },
    // 关闭选择关联产品弹窗
    closeProductModal(bool) {
      this.productVisible = false;
    },
    // 确认关联产品
    comfirmProduct(rows) {
      console.log(rows);
      this.pictureForm.product = [...rows];
      // 删除反选
      // this.pictureForm.product = this.pictureForm.product.filter((item) => {
      //   if (item.type == key) {
      //     let anum = 0
      //     rows.forEach((l) => {
      //       if (item.id == l.id) anum++
      //     })
      //     return anum > 0
      //   } else {
      //     return true
      //   }
      // })
      // // 增加新增
      // rows.forEach((item) => {
      //   let num = 0
      //   this.pictureForm.product.forEach((l) => {
      //     if (item.id == l.id) num++
      //   })
      //   if (num == 0) {
      //     this.pictureForm.product.push({
      //       id: item.id,
      //       name:
      //         item.galleryProductName ||
      //         item.caseProductName ||
      //         item.title ||
      //         item.name,
      //       type: key
      //     })
      //   }
      // })
      // console.log(this.pictureForm.product);
    },
    // 删除关联产品
    deleteProduct(id) {
      this.pictureForm.product.forEach((item, index) => {
        if (item.id == id) {
          this.pictureForm.product.splice(index, 1);
        }
      });
    },
  },
};
</script>
<style lang="less" scoped>
.product {
  color: #00a5ff;
  cursor: pointer;
  width: 60px;
}
.patation {
  position: absolute;
  left: 90px;
  top: 10px;
  color: rgba(0, 0, 0, 0.4);
}
.uploadBox {
  display: flex;
  justify-content: center;
  align-items: center;
  flex-direction: column;
  p {
    text-align: center;
    font-size: 12px;
    margin-top: 4px;
    line-height: 1;
  }
}
.upload_wrap {
  width: 60px;
  height: 60px;
  border: 1px dashed #d9d9d9;
  border-radius: 4px;
  cursor: pointer;
  position: relative;
  .updateImg {
    width: 100%;
    background-color: rgba(0, 0, 0, 0.6);
    color: #fff;
    position: absolute;
    bottom: 0;
    text-align: center;
    white-space: nowrap;
    font-size: 12px;
    line-height: 22px;
  }
}
.upload_wrap:hover {
  border-color: skyblue;
}
</style>
